package com.ruoyi.common.utils;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @ClassName MqttLockUtil
 * @date 2020/12/12
 * @description: TODO 通过缓存来实现mqtt同步
 **/

@Component
public class MqttLockUtil {

    @Autowired
    RedisCache redisCache;

    /**
     * 加锁
     * @param lockNum 锁名称
     * @return
     */
    public  boolean lock(String lockNum){
        String lock = redisCache.getCacheObject(lockNum);
        if (lock != null) {
            return false;
        }
        redisCache.setCacheObject(lockNum,lockNum,15, TimeUnit.SECONDS);

        return true;
    }

    /**
     * 检查锁是否释放
     * @param lockNum 锁名称
     * @param timeout 下发指令后等待时间
     * @return
     */
    public  boolean checkLock(String lockNum,Integer timeout){
        for (int i =0; i < timeout ;i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (redisCache.getCacheObject(lockNum) == null) {

                return true;
            }
        }
        return false;
    }

    /**
     *  释放锁
     * @param lockNum
     * @return
     */
    public  boolean unLock(String lockNum){
        redisCache.deleteObject(lockNum.trim());
        return true;
    }

}
